import { createRouter, createWebHashHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('../layout/index.vue'),
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/dashboard/index.vue'),
        meta: { title: '控制台', icon: 'dashboard' }
      },
      {
        path: 'books',
        name: 'Books',
        component: () => import('../views/books/index.vue'),
        meta: { title: '图书管理', icon: 'book' }
      },
      
      {
        path: 'orders',
        name: 'Orders',
        component: () => import('../layout/RouterView.vue'),
        meta: { title: '订单管理', icon: 'shopping-cart' },
        children: [
          {
            path: '',
            name: 'OrderList',
            component: () => import('../views/orders/OrderList.vue'),
            meta: { title: '订单列表' },
          },
          {
            path: 'detail/:id',
            name: 'OrderDetail',
            component: () => import('../views/orders/OrderDetail.vue'),
            meta: { title: '订单详情' },
            hidden: true
          }
        ]
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('../views/users/index.vue'),
        meta: { title: '用户管理', icon: 'user' }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('../views/profile/index.vue'),
        meta: { title: '个人中心', icon: 'user-filled' },
        children: [
          {
            path: '',
            name: 'ProfileInfo',
            component: () => import('../views/profile/index.vue'),
            meta: { title: '基本资料' },
          },
          {
            path: 'password',
            name: 'ChangePassword',
            component: () => import('../views/profile/index.vue'),
            meta: { title: '修改密码', activeTab: 'changePassword' },
          }
        ]
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/index.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/404.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 判断是否需要登录权限
  if (to.path !== '/login') {
    const token = localStorage.getItem('token')
    if (!token) {
      next('/login')
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router 